<template>
  <div class="app-container">
    <!-- 搜索 -->
    <template>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="120px">
        <el-form-item label="服务项目名称" prop="projectTitle">
          <el-input
            v-model="queryParams.projectTitle"
            placeholder="请输入服务项目名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
          <el-input
            v-model="queryParams.shopId"
            placeholder="请输入店铺ID"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['market:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="projectList"
      row-key="projectId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="projectTitle" label="服务项目名称" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column label="排序" align="center" key="projectSort" prop="projectSort" sortable="custom" :sort-orders="['descending', 'ascending']" width="120" />
      <el-table-column label="随机单是否可用" align="center" key="isAble">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAble"
            active-value="Y"
            inactive-value="N"
            @change="handleIsAbleChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" prop="shopInfo.shopName" min-width="120" v-if="$store.getters && $store.getters.admin" />
      <el-table-column label="操作" align="center" width="240" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['market:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['market:project:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-coin"
            @click="handlePrice(scope.row)"
            v-hasPermi="['market:price:list']"
          >价格</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['market:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="projectOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务项目名称" prop="projectTitle">
              <el-input v-model="form.projectTitle" placeholder="请输入服务项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="projectSort">
              <el-input-number v-model="form.projectSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目详情">
              <editor v-model="form.projectContent" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="isAble">
              <span slot="label">
                随机单是否可用
              </span>
              <el-radio-group v-model="form.isAble">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
              <span slot="label">
                启用状态
              </span>
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, changeProjectStatus, changeProjectIsAble } from "@/api/market/project";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

export default {
  name: "Project",
  dicts: ['sys_yes_no', 'sys_normal_disable'],
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      projectList: [],
      // 菜单表格树数据
      dataList: [],
      // 树最大深度
      deepMax: 4, 
      // 菜单树选项
      projectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100000000,
        projectTitle: undefined,
        shopId: undefined,
        orderByColumn: 'projectSort',
        isAsc: 'ascending',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectTitle: [
          { required: true, message: "服务项目名称不能为空", trigger: "blur" }
        ],
        projectSort: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.dataList = response.rows
        this.projectList = this.handleTree(response.rows, "projectId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.projectId,
        label: node.projectTitle,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listProject(this.queryParams).then(response => {
        this.projectOptions = [];
        const project = { projectId: 0, projectTitle: '主类目', children: [], disabled: true };
        project.children = this.handleTree(response.rows, "projectId");
        this.projectOptions.push(project);
        console.log(this.projectOptions)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: undefined,
        parentId: undefined,
        shopId: undefined,
        projectTitle: undefined,
        projectContent: undefined,
        projectSort: undefined,
        isAble: "Y",
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.projectId) {
        this.form.parentId = row.projectId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加菜单";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getProject(row.projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != undefined) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.dataList.push(this.form)
            if(this.deepMax <= this.calculateMaxDepth(this.projectList, 1)){
              this.$modal.msgError("新增失败，菜单树层级深度不能超过" + this.deepMax + "层");
              return
            }
            
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    
    calculateMaxDepth(nodes, currentDepth) {
      let maxDepth = currentDepth;
      nodes.forEach((node) => {
        if (node.children && node.children.length) {
          const childDepth = this.calculateMaxDepth(node.children, currentDepth + 1);
          maxDepth = Math.max(maxDepth, childDepth);
        }
      });
      return maxDepth;
    },

    /** 价格设置操作 */
    handlePrice: function(row) {
      const projectId = row.projectId;
      // this.$router.push("/market/price-set/project/" + projectId);
      this.$tab.openPage("设置[" + row.projectTitle + "]价格", "/market/price-set/project/" + projectId, row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.projectTitle + '"的数据项？').then(function() {
        return delProject(row.projectId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 服务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.projectTitle + '"服务吗？').then(function() {
        return changeProjectStatus(row.projectId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 随机单是否可用
    handleIsAbleChange(row) {
      let text = row.isAble === "Y" ? "随机单可用" : "随机单不可用";
      this.$modal.confirm('确认要"' + text + '""' + row.projectTitle + '"服务吗？').then(function() {
        return changeProjectIsAble(row.projectId, row.isAble);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isAble = row.isAble === "Y" ? "N" : "Y";
      });
    },
  }
};
</script>
